package com.example.bledemo;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.RequiresPermission;
import androidx.appcompat.app.AppCompatActivity;

import android.bluetooth.le.AdvertiseCallback;
import android.bluetooth.le.AdvertiseData;
import android.bluetooth.le.AdvertiseSettings;
import android.bluetooth.le.BluetoothLeAdvertiser;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.os.ParcelUuid;
import android.os.Bundle;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Build;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Spinner;
import android.widget.ArrayAdapter;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.content.Intent;
import android.net.Uri;
import android.provider.Settings;

import androidx.appcompat.app.AlertDialog;

import android.util.Log;

import com.example.bledemo.ui.IpSettingsActivity;
import com.example.bledemo.ui.MapActivity;
import com.example.bledemo.util.IpSettingsManager;
import com.example.bledemo.util.UuidGenerator;

public class MainActivity extends AppCompatActivity {

    private static final int REQUEST_CODE_BLE_PERMISSIONS = 1001;
    private BluetoothLeAdvertiser bleAdvertiser;
    private AdvertiseCallback advertiseCallback;
    private BluetoothAdapter bluetoothAdapter;
    private boolean isBleStarted = false;
    private static final int MAX_RETRY_COUNT = 3;
    private int retryCount = 0;
    private TextView tvMacAddress;
    private ActivityResultLauncher<Intent> launcher;
    private String[] getRequiredPermissions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            return new String[]{
                    Manifest.permission.BLUETOOTH_ADVERTISE,
                    Manifest.permission.BLUETOOTH_CONNECT,
                    Manifest.permission.BLUETOOTH_SCAN,
                    Manifest.permission.ACCESS_FINE_LOCATION,
                    Manifest.permission.BLUETOOTH,
                    Manifest.permission.BLUETOOTH_ADMIN,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            };
        } else {
            return new String[]{
                    Manifest.permission.BLUETOOTH,
                    Manifest.permission.BLUETOOTH_ADMIN,
                    Manifest.permission.ACCESS_FINE_LOCATION
            };
        }
    }

    private boolean hasAllPermissions() {
        for (String perm : getRequiredPermissions()) {
            if (ContextCompat.checkSelfPermission(this, perm) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    private void markPermissionRequested(String permission) {
        getSharedPreferences("permission_prefs", MODE_PRIVATE)
                .edit().putBoolean(permission, true).apply();
    }

    private boolean hasRequestedPermission(String permission) {
        return getSharedPreferences("permission_prefs", MODE_PRIVATE)
                .getBoolean(permission, false);
    }

    private void requestBlePermissions() {
        for (String perm : getRequiredPermissions()) {
            markPermissionRequested(perm);
        }
        ActivityCompat.requestPermissions(this, getRequiredPermissions(), REQUEST_CODE_BLE_PERMISSIONS);
    }

    // 检查并初始化BLE外设支持
    private boolean initializeBleAdvertiser() {
        if (bluetoothAdapter == null) {
            BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
            bluetoothAdapter = bluetoothManager.getAdapter();
        }

        if (bluetoothAdapter == null) {
            Toast.makeText(this, "设备不支持蓝牙", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (!bluetoothAdapter.isEnabled()) {
            Toast.makeText(this, "请先打开蓝牙", Toast.LENGTH_SHORT).show();
            return false;
        }

        // 延迟初始化bleAdvertiser
        if (bleAdvertiser == null) {
            bleAdvertiser = bluetoothAdapter.getBluetoothLeAdvertiser();
        }

        if (bleAdvertiser == null) {
            retryCount++;
            if (retryCount < MAX_RETRY_COUNT) {
                // 延迟重试
                new android.os.Handler().postDelayed(() -> {
                    Toast.makeText(this, "正在重试初始化BLE外设支持...", Toast.LENGTH_SHORT).show();
                    initializeBleAdvertiser();
                }, 1000);
                return false;
            } else {
                Toast.makeText(this, "设备不支持BLE外设/Beacon模式，请确保蓝牙已开启且设备支持", Toast.LENGTH_LONG).show();
                retryCount = 0;
                return false;
            }
        }

        retryCount = 0;
        return true;
    }
    @RequiresPermission(value = "android.permission.BLUETOOTH_CONNECT")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
        setContentView(R.layout.activity_main);

        Spinner spinnerTxPower = findViewById(R.id.spinner_tx_power);
        Spinner spinnerAdvMode = findViewById(R.id.spinner_adv_mode);
        Button btnStartBle = findViewById(R.id.btn_start_ble);
        Button btnStopBle = findViewById(R.id.btn_stop_ble);
        Button btnServerSettings = findViewById(R.id.btn_server_settings);
        Button btnGoMap = findViewById(R.id.btn_go_map);
        TextView tvStatus = findViewById(R.id.tv_status);
        tvMacAddress = findViewById(R.id.tv_mac_address);

        launcher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == RESULT_OK) {
                        Intent data = result.getData();
                        String value = data.getStringExtra("key");
                        Toast.makeText(this, value, Toast.LENGTH_SHORT).show();
                    }
                }
        );
        boolean isFirst = IpSettingsManager.getFirstBoot(this);



        btnGoMap.setOnClickListener(v -> {
            if (tag==2&&isFirst){
                Intent intent = new Intent(MainActivity.this, MapActivity.class);
                intent.putExtra("labelID",labelID);
                launcher.launch(intent);
            }else {
                Toast.makeText(this, "请先配置好IP 然后打开广播", Toast.LENGTH_SHORT).show();
            }

        });
        // 初始化发射功率下拉框
        String[] txPowerOptions = {"高(High)", "中(Medium)", "低(Low)", "最小(Ultra Low)"};
        int[] txPowerValues = {
                AdvertiseSettings.ADVERTISE_TX_POWER_HIGH,
                AdvertiseSettings.ADVERTISE_TX_POWER_MEDIUM,
                AdvertiseSettings.ADVERTISE_TX_POWER_LOW,
                AdvertiseSettings.ADVERTISE_TX_POWER_ULTRA_LOW
        };
        ArrayAdapter<String> txPowerAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, txPowerOptions);
        txPowerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerTxPower.setAdapter(txPowerAdapter);
        spinnerTxPower.setSelection(0);

        // 初始化广播模式下拉框
        String[] advModeOptions = {"低延迟(Low Latency)", "平衡(Balanced)", "低功耗(Low Power)"};
        int[] advModeValues = {
                AdvertiseSettings.ADVERTISE_MODE_LOW_LATENCY,
                AdvertiseSettings.ADVERTISE_MODE_BALANCED,
                AdvertiseSettings.ADVERTISE_MODE_LOW_POWER
        };
        ArrayAdapter<String> advModeAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, advModeOptions);
        advModeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinnerAdvMode.setAdapter(advModeAdapter);
        spinnerAdvMode.setSelection(0);

        BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter();
        // 移除过早的bleAdvertiser初始化，改为延迟初始化
        // bleAdvertiser = bluetoothAdapter.getBluetoothLeAdvertiser();

        btnStartBle.setOnClickListener(v -> {
            if (!hasAllPermissions()) {
                requestBlePermissions();
                return;
            }

            // 使用新的初始化方法
            if (!initializeBleAdvertiser()) {
                return;
            }

            int txPower = txPowerValues[spinnerTxPower.getSelectedItemPosition()];
            int advMode = advModeValues[spinnerAdvMode.getSelectedItemPosition()];

            // 强制清空设备名称
//            try {
//                Log.i("BLE", "设置前蓝牙适配器名称: " + bluetoothAdapter.getName());
//                // 尝试设置为最小化名称而不是空字符串
//                bluetoothAdapter.setName("01"); // 使用最小化名称
//                Log.i("BLE", "设置蓝牙适配器名称为最小化名称: AOA");
//                // 延迟检查名称是否真的被设置
//                new android.os.Handler().postDelayed(() -> {
//                    String currentName = bluetoothAdapter.getName();
//                    Log.i("BLE", "设置后延迟检查蓝牙适配器名称: " + currentName);
//                    if (currentName == null || currentName.isEmpty()) {
//                        Log.w("BLE", "警告：蓝牙适配器名称为空，可能使用系统默认名称");
//                    }
//                }, 1000);
//            } catch (Exception e) {
//                Log.w("BLE", "无法设置设备名称: " + e.getMessage());
//            }
            
//            Log.i("BLE", "当前蓝牙适配器名称: " + bluetoothAdapter.getName());

            // 将参数保存为 final 变量，以便在延迟回调中使用

            final int finalTxPower = txPower;
            final int finalAdvMode = advMode;


            // 添加延迟，确保设备名称更新生效
            new android.os.Handler().postDelayed(() -> {
//                Log.i("BLE", "延迟后的设备名称: " + bluetoothAdapter.getName());
               //" 静止状态 (status=0) 运动状态 (status=1)  行车状态 (status=2)
                startBeaconAdvertise(finalTxPower, finalAdvMode, 0);
                isBleStarted = true;
                tvStatus.setText("状态: Beacon 广播中");
                btnStartBle.setEnabled(false);
                btnStopBle.setEnabled(true);
                Toast.makeText(this, "Beacon 广播已启动", Toast.LENGTH_SHORT).show();
            }, 500); // 延迟500毫秒
        });

        btnStopBle.setOnClickListener(v -> {
            if (isBleStarted) {
                tag=1;
                stopBeaconAdvertise();
                isBleStarted = false;
                tvStatus.setText("状态: 已停止");
                tvMacAddress.setVisibility(View.GONE);
                btnStartBle.setEnabled(true);
                btnStopBle.setEnabled(false);
                Toast.makeText(this, "Beacon 广播已停止", Toast.LENGTH_SHORT).show();
            }
        });

        // 服务器设置按钮点击事件
        btnServerSettings.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this,IpSettingsActivity.class);
            startActivity(intent);
        });

        // 跳转地图界面


        // 初始状态
        btnStopBle.setEnabled(false);
        tvStatus.setText("状态: 未启动");
        tvMacAddress.setVisibility(View.GONE);
    }

    private int tag=1;
    private String labelID="";


    private void startBeaconAdvertise(int txPower, int advMode,int currentStatus) {
        AdvertiseSettings settings = new AdvertiseSettings.Builder()
                .setAdvertiseMode(advMode)
                .setConnectable(true)
                .setTimeout(0)
                .setTxPowerLevel(txPower)
                .build();
         UuidGenerator.WechatUuidData uuidData = UuidGenerator.generateWechatUuids(currentStatus);
        UuidGenerator.printUuidDetails(uuidData);
        labelID=uuidData.tagId;
        AdvertiseData.Builder dataBuilder = new AdvertiseData.Builder();
//        // 不包含设备名称和TxPower，确保广播数据纯净
//        dataBuilder.setIncludeDeviceName(true);
//        dataBuilder.setIncludeTxPowerLevel(true);
        // 添加Service UUIDs - 将27字节数据分解为13个16位UUID + 1个8位数据
//        String[] uuidStrings = {
//            "00000100-0000-1000-8000-00805f9b34fb",  // 0001
//            "0000725f-0000-1000-8000-00805f9b34fb",  // 5F72
//            "0000c0b0-0000-1000-8000-00805f9b34fb",  // C0B0
//            "0000bd50-0000-1000-8000-00805f9b34fb",  // 50BD
//            "0000b184-0000-1000-8000-00805f9b34fb",  // 84B1
//            "00009f32-0000-1000-8000-00805f9b34fb",  // 329F
//            "00009d14-0000-1000-8000-00805f9b34fb",  // 149D
//            "00006fdd-0000-1000-8000-00805f9b34fb",  // DD6F
//            "000010d3-0000-1000-8000-00805f9b34fb",  // D310
//            "0000380f-0000-1000-8000-00805f9b34fb",  // 0F38
//            "00002d72-0000-1000-8000-00805f9b34fb",  // 722D
//            "00005ea8-0000-1000-8000-00805f9b34fb",  // A85E
//            "000058c2-0000-1000-8000-00805f9b34fb"   // C258
//        };
//
//        // 添加所有Service UUID
//        for (String uuidString : uuidStrings) {
//            try {
//                ParcelUuid uuid = new ParcelUuid(UUID.fromString(uuidString));
//                dataBuilder.addServiceUuid(uuid);
//            } catch (Exception e) {
//                Log.e("BLE", "无效的UUID: " + uuidString);
//            }
//        }
        // 添加服务UUID (转换为Android格式)
        for (String uuid : uuidData.serviceUuids) {
            // 将4位十六进制字符串转换为标准UUID格式
//            Log.i("BLE", "fullUuid:..."+uuid);
            String fullUuid = String.format("0000%s-0000-1000-8000-00805f9b34fb", uuid);

            dataBuilder.addServiceUuid(ParcelUuid.fromString(fullUuid));
        }

        advertiseCallback = new AdvertiseCallback() {
            @Override
            public void onStartSuccess(AdvertiseSettings settingsInEffect) {
                super.onStartSuccess(settingsInEffect);
                Log.i("BLE", "AOA Beacon 广播启动成功");
                tag=2;
                runOnUiThread(() -> {
                    String macAddress = "未知";
                    String additionalInfo = "";

                    try {
                        if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
                            String address = bluetoothAdapter.getAddress();
                            if (address != null && !address.equals("02:00:00:00:00:00") && !address.equals("01:00:00:00:00:00")) {
                                macAddress = address;
                                additionalInfo = " (静态地址)";
                            } else {
                                macAddress = "隐私保护模式";

                            }
                        } else {
                            macAddress = "权限不足";
                        }
                    } catch (Exception e) {
                        Log.e("BLE", "获取MAC地址失败: " + e.getMessage());
                        macAddress = "获取失败";
                    }
                    additionalInfo = " (MAC地址随机化，扫描时会变化)"+"当前TAG:"+ labelID;;
                    tvMacAddress.setText("MAC地址: " + macAddress + additionalInfo );
                    tvMacAddress.setVisibility(View.VISIBLE);
                });
            }
            @Override
            public void onStartFailure(int errorCode) {
                super.onStartFailure(errorCode);
                Log.e("BLE", "AOA Beacon 广播启动失败: " + errorCode);
                String errorMsg = "未知错误";
                tag=1;
                switch (errorCode) {
                    case 1: errorMsg = "数据过大"; break;
                    case 2: errorMsg = "设备不支持"; break;
                    case 3: errorMsg = "资源不足"; break;
                    case 4: errorMsg = "内部错误"; break;
                    case 5: errorMsg = "参数无效"; break;
                }
                String finalErrorMsg = errorMsg;
                runOnUiThread(() -> Toast.makeText(MainActivity.this, "AOA广播启动失败: " + finalErrorMsg + "(" + errorCode + ")", Toast.LENGTH_SHORT).show());
            }
        };
        
//        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADVERTISE) != PackageManager.PERMISSION_GRANTED) {
//            Log.i("BLE", "checkSelfPermission...");
//            return;
//        }

        Log.i("BLE", "开始发送AOA广播数据...");
        bleAdvertiser.startAdvertising(settings, dataBuilder.build(), advertiseCallback);
    }


    private void stopBeaconAdvertise() {
        if (bleAdvertiser != null && advertiseCallback != null) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADVERTISE) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            bleAdvertiser.stopAdvertising(advertiseCallback);
            runOnUiThread(() -> tvMacAddress.setVisibility(View.GONE));
        }
     }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_BLE_PERMISSIONS) {
            if (hasAllPermissions()) {
                Toast.makeText(this, "权限已授予，请重新点击打开", Toast.LENGTH_SHORT).show();
            } else {
                boolean someDeniedPermanently = false;
                StringBuilder deniedPermissions = new StringBuilder();
                for (int i = 0; i < permissions.length; i++) {
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        deniedPermissions.append(permissions[i]).append("\n");
                        // 只有用户曾经请求过且 shouldShowRequestPermissionRationale 返回 false 时，才认为是永久拒绝
                        if (!ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[i]) && hasRequestedPermission(permissions[i])) {
                            someDeniedPermanently = true;
                        }
                    }
                }
                if (deniedPermissions.length() > 0) {
                    Log.w("BLE_PERMISSION", "被拒绝的权限:\n" + deniedPermissions.toString());
                    Toast.makeText(this, "被拒绝的权限:\n" + deniedPermissions.toString(), Toast.LENGTH_LONG).show();
                }
                if (someDeniedPermanently) {
                    new AlertDialog.Builder(this)
                            .setTitle("权限申请")
                            .setMessage("部分权限被永久拒绝，请在设置中手动开启相关权限，否则无法使用BLE功能。")
                            .setPositiveButton("去设置", (dialog, which) -> {
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                intent.setData(Uri.parse("package:" + getPackageName()));
                                startActivity(intent);
                            })
                            .setNegativeButton("取消", null)
                            .show();
                } else {
                    Toast.makeText(this, "缺少必要权限，无法启动BLE外设", Toast.LENGTH_SHORT).show();
                }
            }
        }
    }
}